
package com.compuvest.amazon

import javax.servlet.ServletConfig

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/amazon/MakeOrder")
class AmazonMakeOrder extends HttpServlet {

    def mysql
    //def session
    def gmail

    def void init(ServletConfig config) {
	super.init(config)

        mysql = new AmazonSQLService()

        // init google email
        gmail = new GoogleEmail()
        //def props = new Properties()
        //props.put("mail.smtp.host", "mail1.compuvest.com")

        //session = Session.getDefaultInstance(props, null)
    }

    def void processRequest(request, response) {

        def result = new StringBuilder()

        def exec = request.getParameter("exec")
        if(exec) {
            if(exec == 'order') {

                def xml = getXML(request)
                //println "amazon xml:\n${xml}"
                //def xml = getXMLTest()
                if(xml.status == "OK") {

                    def customer = parseXML(xml.body)
                    if(customer.status == "OK") {

                        // write to database
                        def order = mysql.fillCustomer(customer)
                        if(order.status == "OK") {
                            // send email
                            def basket = mysql.getBasket(order.orderNo)
                            if(basket.status == "OK") {
                                sendEmail(customer, order, basket)

                                mysql.setImport(order.orderNo)

                                result << "<result amazonNo='${order.amazonNo}' compuvestNo='${order.orderNo}'><status>OK</status></result>"
                            }
                            else {
                                println "getBasket: ${basket.body}"
                                result << "<result><status>ERROR</status><message>${basket.body}</message></result>"
                            }
                        }
                        else if(order.status == "DONE") { // imported
                            result << "<result><status>OK</status><message>${order.body}</message></result>"
                        }
                        else {
                            println "fillCustomer: ${order.body}"
                            result << "<result><status>ERROR</status><message>${order.body}</message></result>"
                        }
                    }
                    else if(customer.status == "CANCEL") {
                        def order = mysql.cancelOrder(customer.amazonNo)
                        if(order.status == "OK") {
                            result << "<result><status>OK</status><message>Amazon Order ${customer.amazonNo} CANCELLED</message></result>"
                        }
                        else {
                            println "cancelOrder ${order.body}"
                            result << "<result><status>ERROR</status><message>${order.body}</message></result>"
                        }
                    }
                    else {
                        println "parseXML: ${customer.body}"
                        result << "<result><status>ERROR</status><message>${customer.body}</message></result>"
                    }
                }
                else {
                    println "getXML: ${xml.body}"
                    result << "<result><status>ERROR</status><message>${xml.body}</message></result>"
                }
            }
            else if(exec == 'request') {
                // take not imported order form database
                def amazonNoList = mysql.getAmazonNumbers()
                if(amazonNoList.size() != 0) {
                    amazonNoList.each { amazonNo->

                        try {
                            "http://10.0.1.93/amazonmws/neworder.ashx?amazonNo=${amazonNo}".toURL().text
                        }
                        catch(error) {
                            println "request 10.0.1.93/ to Vlad service Error: ${error}"
                        }
                        //result << "<result><status>OK</status><message>${xml}</message></result>"
                    }

                    // set was request
                    mysql.setAmazonNumbersInActive(amazonNoList)
                }
                else {
                    result << "<result><status>OK</status><message>Dont have orders</message></result>"
                }
            }

        }

        response.setContentType("text/xml;charset=UTF-8")
        def out = response.getWriter()
        try {
            out.print(result.toString())
        }
        finally {
            out.close()
        }
    }

    def getXML(request) {

        def stringBuffer = new StringBuilder()
        def bytes = new byte[4096]

        def inputStream
        try {
            inputStream = request.getInputStream()
            for(int n; (n = inputStream.read(bytes)) != -1; ) {
                stringBuffer << new String(bytes, 0, n)
            }
        }
        catch(error) {
            return ["status": "ERROR", "body": error]
        }

        return ["status": "OK", "body": new String(stringBuffer.toString())]
    }

    def getXMLTest() {

        def xml = 'http://10.0.7.30/Admin/amazon/SendTest'.toURL().text
        //println "xml=${xml}"

        return ["status": "OK", "body": xml]
    }

    def parseXML(xml) {

        //println "xml=${xml}"
        def root
        try {
            root = new XmlSlurper().parseText(xml)
        }
        catch(error) {
            return ["status": "ERROR", "body": error]
        }

        if(root.name() == "orders") {
            try {
                if(root.order.status == "OK") {
                    def email = root.order.email.text()
                    if(! email) {
                        return ["status": "ERROR", "body": "XML empty"]
                    }
                    def name = root.order.name.text()
                    def zip = root.order.zipcode.text()
                    def country = root.order.country.text()
                    def state = root.order.state.text()
                    def addr1 = root.order.address1.text()
                    def addr2 = root.order.address2.text() + ' ' + root.order.address3.text()
                    return [
                        "status"    : "OK",
                        "body"      : "",
                        "amazonNo"  : root.order.@amazonNo.text(),
                        "email"     : email,
                        "firstname" : name.substring(0, (name.indexOf(' ') > 0 ? name.indexOf(' ') : name.length())),
                        "lastname"  : name.substring((name.indexOf(' ') > 0 ? name.indexOf(' ') + 1 : name.length()), name.length()),
                        "address1"  : addr1.length() > 50 ? addr1[0..49] : addr1,
                        "address2"  : addr2.length() > 50 ? addr2[0..49] : addr2,
                        "city"      : root.order.city.text(),
                        "state"     : state.length() > 15 ? state[0..14] : state,
                        "country"   : country.length() > 2 ? country[0..1] : country,
                        "zip"       : zip.substring(0, (zip.indexOf('-') > 0 ? zip.indexOf('-') : zip.length())),
                        "zip4"      : zip.substring((zip.indexOf('-') > 0 ? zip.indexOf('-') + 1 : zip.length()), zip.length()),
                        "phone"     : root.order.phone.text(),
                    ]
                }
                else if(root.order.status == "CANCEL") {
                    return ["status": "CANCEL", "body": "", "amazonNo"  : root.order.@amazonNo.text()]
                }
            }
            catch(error) {
                return ["status": "ERROR", "body": error]
            }
        }

        return ["status": "ERROR", "body": "Nothink do"]
    }

    def sendEmail(cust, order, basket) {

        //println "-----sendEmail-----\n" +
        //        "cust=${(cust ? cust : 'Empty or null')}\n" +
        //        "order=${(order ? order : 'Empty or null')}\n" +
        //        "basket=${(basket ? basket : 'Empty or null')}\n" +
        //        "---------------"

        def body = new StringBuilder()
        StringBuilder shipBody = new StringBuilder()

        body << "AMAZON PAYMENT\n\n"
        body << "Confirmation Number:\t${order.orderNo}\n"
        body << "Amazon Number:\t\t${cust.amazonNo}"
        body << "\n\nItemNo\t\tQty\tPrice\t\tAmount\tItem Name"

        def items = basket["items"]
        items.each { key,item->
            body << "\n${item.accwareID}\t${item.qty}\t${String.format("\$%6.2f",item.sellprice)}\t\t${String.format("\$%6.2f",item.qty * item.sellprice)}\t${item.name}"
            //body.append(item.getPromotionPriceString(true));
            if(item.warnprice != 0d) {
                body << "\n***warranty:\t${item.warndesc}\t${String.format("\$%6.2f",item.qty * item.warnprice)} for #${item.accwareID}"
            }

            //println "key=${key} : item1=${item.accwareCatID} : item2=${item["accwareCatID"]}"
        }
        body << "\n------------------------------------------------------\n"
        def couponPrice = 0d;
        if(basket.couponCode) {
            couponPrice = basket.couponProcent ? basket.amount - (basket.amount - (basket.amount / 100 * basket.couponProcent)) : basket.couponPrice

            body << "Coupon\t: CV${basket.couponCode}  ${String.format("\$%6.2f",couponPrice)}\n"
        }
        body << "Total\t: ${String.format("\$%6.2f",basket.amount - couponPrice)}\n"
        if(basket.tax != 0d) {
            body << "WA Tax\t: ${String.format("\$%6.2f",basket.tax)}\n"
        }
        body << "Shipping:\t${String.format("\$%6.2f",basket.ship_price)} ${basket.ship_code}\n"
        body << "Grand Total\t: ${String.format("\$%6.2f",(basket.amount - couponPrice) + basket.tax + basket.ship_price)}"

        body << "\n\n\nShip Name:\t\t${cust.firstname + " " + cust.lastname}"
        body << "\nShip Address:\t${cust.address1 + " " + cust.address2}"
        body << "\n\t\t\t${cust.zip + " " + cust.zip4} ${cust.city},${cust.state} ${cust.country}"
        body << "\nShip Phone:\t\t${cust.phone}"
        body << "\n\nEmail:\t\t${cust.email}"
/*
	if(basket.getPromotion() != null) {
            body << "\n${basket.getCouponMessage(false)}"
	}
        body << "\nTotal Amount:\t\t${priceDF.format(basket.getTotal(true))}"
*/

        // send gmail
        gmail.send(
            "webserver@compuvest.com",
            ["ordersamazon@compuvest.com"] as String[],
            "Order From Compuvest.com Amazon payment #${order.orderNo}" as String,
            body.toString(),
            "text/plain"
        )
    }

    def void doGet(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    def void doPost(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    String getServletInfo() {
        return "AmazonMakeOrder"
    }
    def void destroy() {
        mysql = null
    }
}
